# src/db/user_db.py
from src.db.connection import get_db_connection, close_db_connection
from src.utils.logger import get_logger

logger = get_logger(__name__)

def get_user_by_username(username: str) -> dict:
    """通过用户名查询用户（返回字典格式）"""
    conn = get_db_connection()
    if not conn:
        return None
    
    try:
        with conn.cursor() as cursor:
            sql = "SELECT * FROM user WHERE username = %s"
            cursor.execute(sql, (username,))
            user = cursor.fetchone()  # 返回单条记录（字典）
            return user
    except Exception as e:
        logger.error(f"查询用户失败（username: {username}）：{str(e)}")
        return None
    finally:
        close_db_connection(conn)

def create_user(
    username: str,
    hashed_password: str,
    real_name: str,
    contact_info: str,
    address: str = "",
    user_role: str = "买家"
) -> bool:
    """创建新用户（返回是否成功）"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        with conn.cursor() as cursor:
            # 1. 先检查用户名是否已存在
            if get_user_by_username(username):
                logger.warning(f"用户名已存在（username: {username}）")
                return False
            
            # 2. 插入新用户
            sql = """
            INSERT INTO user 
            (username, password, real_name, contact_info, address, user_role, create_time)
            VALUES (%s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP)
            """
            cursor.execute(
                sql,
                (username, hashed_password, real_name, contact_info, address, user_role)
            )
            conn.commit()
            logger.info(f"用户创建成功（username: {username}）")
            return True
    except Exception as e:
        conn.rollback()
        logger.error(f"创建用户失败（username: {username}）：{str(e)}")
        return False
    finally:
        close_db_connection(conn)

def get_user_by_id(user_id: int) -> dict:
    """通过用户ID查询用户（用于关联查询）"""
    conn = get_db_connection()
    if not conn:
        return None
    
    try:
        with conn.cursor() as cursor:
            sql = "SELECT * FROM user WHERE user_id = %s"
            cursor.execute(sql, (user_id,))
            return cursor.fetchone()
    except Exception as e:
        logger.error(f"查询用户失败（user_id: {user_id}）：{str(e)}")
        return None
    finally:
        close_db_connection(conn)